package edu.hawaii.duedates.libraries;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

import edu.hawaii.duedates.Book;
import edu.hawaii.duedates.Library;
import edu.hawaii.duedates.LibraryUser;

/**
 * This contains the classes for accessing the Hawaii's State Library.
 * 
 * @author Anthony Du, Vincent Leung
 */
public class HSLLibrary extends Library {
  // Library name
  private static String HSL_NAME = "Hawaii State Library";
  
  /**
   * Default HSLLibrary constructor.
   */
  public HSLLibrary() {
    this.setLibName(HSL_NAME);
  }

  /**
   * Attempts to login to the Hawaii State Library System.
   * @param user LibraryUser object. 
   * @return The WebConversation after logging in. 
   * @throws Exception If errors occur while logging in. 
   */
  @Override
  protected WebConversation logIntoLibrary(LibraryUser user) throws Exception {
    try {
      String url = "http://www.librarieshawaii.org/";
      // Website has bogus JavaScript code.
      HttpUnitOptions.setExceptionsThrownOnScriptError(false);
      // create the conversation object which will maintain state for us
      WebConversation conversation = new WebConversation();
      WebRequest request = new GetMethodWebRequest(url);
      WebResponse response = conversation.getResponse(request);
      WebLink link = response.getLinkWith("My Account");
      link.click();
      response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      form.setParameter("sec1", user.getId());
      form.setParameter("sec2", user.getPassword());
      form.submit();
      response = conversation.getCurrentPage();
      WebTable table = response.getTables()[3];
      String s = table.getCellAsText(0, 0).trim(); 
      String faillogin = "Login failed.  Please check your barcode and pin and try again.";
      if (s.equals(faillogin)) {
        System.out.println("Login failed.  Please check your barcode and pin and try again.");
        throw new Exception("Error while logging in to HSL Library");
      }
      return conversation;
    }
    catch (Exception e) {
      throw new Exception ("Error while logging in to Hawaii State Library", e);
    }
  }

  /**
   * Gets info from the Hawaii State Library site.
   * @return A string providing information about checked out books. 
   * @param user LibraryUser object. 
   * @throws Exception If problems occur getting the information. 
   */
  @Override
  public String getLibInfo(LibraryUser user) throws Exception {
    String dateFormat = "MM/dd/yy";
    SimpleDateFormat formattedDate = new SimpleDateFormat(dateFormat, Locale.US); 
    try {
      WebConversation conversation = this.logIntoLibrary(user);
      WebResponse response = conversation.getCurrentPage();
      WebLink link = response.getLinkWith("Items Out");
      link.click();
      response = conversation.getCurrentPage();
      WebTable table = response.getTableStartingWith("Title");
      if (table == null) {
        return "No books checked out";
      }
      int rowCount = table.getRowCount();
      for (int i = 1; i < rowCount; i++) {
          String bookInfo = table.getCellAsText(i, 0);
          String dueDate = table.getCellAsText(i, 2);
          Date duedate = formattedDate.parse(dueDate);
          this.addBook(new Book(bookInfo, duedate));
      }
      return null;
    }
    catch (Exception e) {
      throw new Exception("Error getting Hawaii State Library info", e);
    }
  }
}